const api = require('../../utils/api.js');
const utils = require('../../utils/utils.js');
const { gatherAction = '', reportAction = '' } = require('../../utils/utils');
const tools = require('../../utils/getuserinfo.js');
const internal = require('../../utils/international.js');
const app = getApp();
const { module: moduleName } = app.siteInfo;
const util = app.util;

Page({
  data: {
    id: null,
    goods: {},
    show_attr_picker: false,
    form: {
      number: 1,
    },
    idx: 1,
    level: 0,
    comment_list: [],
    comment_count: {
      score_all: 0,
      score_6: 0,
      score_3: 0,
      score_2: 0,
      score_1: 0,
    },
    autoplay: true,
    img_hide: true,
    hide: 'hide',
    x: wx.systemInfo.windowWidth,
    y: wx.systemInfo.windowHeight - 20,
    miaosha_end_time_over: {
      h: '--',
      m: '--',
      s: '--',
    },
    attachment_url: app.siteInfo.attachment_url,
    theme: app.themeData,
    abnorData: {
      imgSrc: '/common/static/images/abnor-09.png',
      text: '暂无相关评价',
    },
    abnorData1: {
      imgSrc: '/common/static/images/abnor-02.png',
      text: '暂无评论,快去占沙发哦~',
    },
    down: false,
    down1: false,
    show_service: false,
    unit: '',
    showreply: false,
    showInput: false,
    commentlist: [],
    cPage: 1,
    cMore: true,
    recommendlist: [],
    product: {},
    matchGoods: [],
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    imgUrl: app.imgUrl,
    goods_buy_now: internal.getOrderStatus('goods_buy_now'),
    isPosterTitleShow: internal.getOrderStatus('isPosterTitleShow'),
  },

  onLoad(op) {
    this.setData({
      useTabbar: this.data.useTabbar && app.getTabBarStatus(),
    });
    app.v8_card_seller_actions_log = [];
    app.v8_card_action_log = [];
    let options = op || {};
    app.tabbarindex = options.tabbarindex
      ? options.tabbarindex - 0
      : app.tabbarindex;
    app.pageOnLoad(this);
    wx.showLoading({
      title: '正在加载...',
    });
    let userinfo = wx.getStorageSync('user_info');
    let store = wx.getStorageSync('store');
    let share_setting = wx.getStorageSync('share_setting');
    let that = this;
    let parent_id = 0;
    let shop_id = 0;
    let share_scene = '';
    let user_id = options.user_id;
    let scene = decodeURIComponent(options.scene);
    if (options && options.share_openid && options.room_id){
      that.getBind(options.room_id,options.share_openid,0)
    }
    if (options && options.shopid) {
      app.ws_micro_shop_globalData.shopid = options.shopid;
      shop_id = options.shopid;
    }
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    if (user_id) {
      parent_id = user_id;
      share_scene = 4;
    } else if (scene) {
      let { uid, gid, sid, g_id } = utils.scene_decode(scene);
      if (g_id && gid) {
        app.ws_micro_shop_globalData.last_share_guide_id = g_id;
        app.ws_micro_shop_globalData.last_share_good_id = gid;
        app.ws_micro_shop_globalData.shopid = sid;
        options.id = gid;
        options.guide_id = g_id;
        options.shopid = sid;
        shop_id = sid;
      }
      if (gid) {
        parent_id = uid;
        options.id = gid;
        shop_id = sid;
        app.ws_micro_shop_globalData.shopid = sid;
      } else {
        parent_id = scene;
      }
      share_scene = 6;
    }
    parent_id && (app.ws_micro_shop_globalData.parent_id = parent_id);

    // 准备在线客服button需要的参数
    let sessionFormStr = {
      shop_id: app.ws_micro_shop_globalData.shopid,
    };
    let serviceMessageTitle = '';
    let serviceMessagePath = 'goods?id=' + options.id;

    app.loadShopSetting()
      .then(res => {
        that.setData(res);
      })
      .then(() => {
        that.getFloatIcon();
      });
    if (userinfo && store) {
      Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
      Number(store.comment_switch) === 1 && this.getComments(options.id, 0, 1);
      this.setData({
        store,
        orgPrice: store.show_original_price && store.show_original_price == 1 ? 1 : 0
      });
      app.ws_micro_shop_globalData.orgPrice = this.data.orgPrice;
      app.loginBindParent({
        parent_id,
        shop_id,
        share_scene,
      });
      util.prepareBindInfo(options, moduleName, that);
      this.bindCard(options);
      app.bindGuide(options);
    } else {
      app.ws_micro_shoplogin().then(res => {
        userinfo = wx.getStorageSync('user_info');
        Number(userinfo.info) === 0 &&
          tools.onGetInfo(that, userinfo.auth_mode);
        util.prepareBindInfo(options, moduleName, that);
        this.bindCard(options);
        app.bindGuide(options);
        app.getStoreData().then(res => {
          store = wx.getStorageSync('store');
          Number(store.comment_switch) === 1 &&
            that.getComments(options.id, 0, 1);
          that.setData({
            store,
            orgPrice: store.show_original_price && store.show_original_price == 1 ? 1 : 0
          });
          app.ws_micro_shop_globalData.orgPrice = this.data.orgPrice;
          
          app.loginBindParent({
            parent_id,
            shop_id,
            share_scene,
          });
        });
      });
    }
    if (options.guide_id) {
      app.ws_micro_shop_globalData.last_share_guide_id = options.guide_id;
      app.ws_micro_shop_globalData.last_share_good_id = options.id;
    }
    if (options.room_id) {
      app.ws_micro_shop_globalData.last_room_id = options.room_id;
      app.ws_micro_shop_globalData.last_room_good_id = options.id;
    }
    
    this.setData({
      opts: options,
      id: options.id,
      parent_id,
      shop_id,
      share_scene,
      sessionFormStr: JSON.stringify(sessionFormStr),
      serviceMessageTitle,
      serviceMessagePath,
      commission_alias: share_setting.commission_alias || '佣金',
      isMulti: app.ws_micro_shop_globalData.isMulti,
      isSaas: app.ws_micro_shop_globalData.isSaas,
    });
    // this.getGoods();
    // this.loadGoodsRecommend(options.id); 
  },

  getBind(roomid,parent_id,from_type){
    app.util.request({
      url: 'live/live/bind',
      data: {
        roomid: roomid,
        parent_id,
        from_type
      },
      success:res=>{
        console.log('直播分销绑定成功',res)
      }
    })
  },


  onReady() {
    wx.onUserCaptureScreen(() => {
      gatherAction &&
        gatherAction('screenshots', 'success', { goodsID: this.data.id });
    });
  },

  onShow() {
    this.setData({ matchGoods: [] });
    this.getGoods();
    this.loadGoodsRecommend(this.data.opts.id);

    let { fromHome } = this.data.opts;
    if (Number(fromHome) === 1) {
      let pages = getCurrentPages(); //  获取页面栈
      let prevPage = pages[pages.length - 2]; // 上一个页面
      prevPage.setData({
        fromHome: true,
      });
    }
  },

  onHide() {
    util.sendBindInfo(this.data);
    reportAction && reportAction();
  },

  onUnload() {
    util.sendBindInfo(this.data);
    reportAction && reportAction();
  },

  bindCard(options) {
    app.bindCard(options.openid, options.share_scene);
    app.v8_card_action_log.push({ name: 'transmitGoods', data:{goodsID: options.id, type: 'comm'}, timestamp: new Date().getTime(), to_openid: options.openid });
    app.util.statRequest({
      aa: JSON.stringify(app.v8_card_action_log),
      is_module: 0
    });
  },

  getGoods() {
    let _this = this;
    let { id, goods } = _this.data;
    app.ws_micro_shoprequest({
      url: api.default.goods,
      data: {
        id,
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let resp = res.data;
          let pic = [];
          for (let i in resp.pic_list) {
            if (resp.pic_list.hasOwnProperty(i)) {
              pic.push(resp.pic_list[i].pic_url);
            }
          }
          let product = {
            item_code: String(resp.id),
            title: resp.name,
            desc: resp.detail,
            category_list: resp.category,
            image_list: pic,
            src_mini_program_path:
              '/ws_micro_shop/pages/goods/goods?id=' + resp.id,
          };
          _this.setData({
            goods: resp,
            product,
            attr_group_list: resp.attr_group_list,
            serviceMessageTitle: product.title || '',
          });
          goods.miaosha && _this.setMiaoshaTimeOver();
          _this.selectDefaultAttr();
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                app.util.navigateTo('/ws_micro_shop/pages/index/index');
              }
            },
          });
        }
        if (res.code === -3) {
          app.ws_micro_shoplogin().then(res => {
            let userinfo = wx.getStorageSync('user_info');
            Number(userinfo.info) === 0 &&
              tools.onGetInfo(_this, userinfo.auth_mode);
            util.prepareBindInfo(_this.data.opts, moduleName, _this);
            app.getStoreData().then(res => {
              let store = wx.getStorageSync('store');
              Number(store.comment_switch) === 1 &&
                _this.getComments(_this.data.opts.id, 0, 1);
              _this.setData({
                store,
              });
              app.loginBindParent({
                parent_id: _this.data.parent_id,
                shop_id: _this.data.shop_id,
                share_scene: _this.data.share_scene,
              });
            });
            _this.getGoods();
          });
        }
      },
    });
  },

  checkDesc() {
    this.setData({
      down: !this.data.down,
    });
  },

  checkDesc1() {
    this.setData({
      down1: !this.data.down1,
    });
  },

  selectDefaultAttr() {
    let _this = this;
    let { attr_group_list, goods } = _this.data;
    if (!goods || Number(goods.use_attr) !== 0) {
      return;
    }
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        for (let j in attr_group_list[i].attr_list) {
          if (Number(i) === 0 && Number(j) === 0) {
            attr_group_list[i].attr_list[j]['checked'] = true;
          }
        }
      }
    }
    _this.setData({
      attr_group_list,
    });
  },

  getComments(id, score, page) {
    let _this = this;
    app.ws_micro_shoprequest({
      url: api.default.comment_list,
      method: 'GET',
      data: {
        goods_id: id,
        score,
        page,
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let { list, comment_count, good_per, star_sum } = res.data;
          if (list.length > 0) {
            good_per = good_per.split('.')[0];
            _this.setData({
              comment_count,
              comment_list: _this.data.comment_list.concat(list.splice(0, 1)),
              good_per,
              star_sum,
            });
          }
        }
      },
    });
  },

  onGoodsImageClick(e) {
    let urls = [];
    let index = e.currentTarget.dataset.index;
    let pic_list = this.data.goods.pic_list;
    for (let i in pic_list) {
      if (Object.prototype.hasOwnProperty.call(pic_list, i)) {
        urls.push(pic_list[i].pic_url);
      }
    }
    wx.previewImage({
      urls: urls,
      current: urls[index],
    });
    gatherAction &&
      gatherAction('onGoodsImageClick', 'success', { goodsID: this.data.id });
  },

  numberSub() {
    let num = this.data.form.number;
    if (num <= 1) {
      return true;
    }
    num--;
    this.setData({
      form: {
        number: num,
      },
    });
  },

  numberAdd() {
    let num = this.data.form.number;
    num++;
    this.setData({
      form: {
        number: num,
      },
    });
  },

  numberBlur(e) {
    let num = e.detail.value;
    num = parseInt(num, 10);
    (isNaN(num) || num <= 0) && (num = 1);
    this.setData({
      form: {
        number: num,
      },
    });
  },

  addCart() {
    if (this.data.matchGoods.length >= 1) {
      return wx.showModal({
        title: '提示',
        content: '选择搭配商品后，不能加入购物车。请直接购买',
        showCancel: false,
      });
    } else {
      this.submit('ADD_CART');
    }
  },

  buyNow() {
    this.submit('BUY_NOW');
  },

  submit(type) {
    let _this = this;
    let goods = _this.data.goods;
    let member_only = goods.member_only;
    let userInfo = wx.getStorageSync('user_info');
    if (Number(member_only) === 1 && userInfo && userInfo.level === -1) {
      wx.showModal({
        title: '提示',
        content: '您还不是会员,不能购买此商品',
        showCancel: false,
        success(res) {},
      });
      return false;
    }
    let buycount = Number(_this.data.form.number);
    if (goods.member_card_info) {
      if (Number(goods.member_card_info.has_member_card) === 1) {
        if (
          Number(goods.index_member_only) === 1 &&
          Number(goods.index_buy_limit) > 0 &&
          (Number(goods.index_order_count) >= Number(goods.index_buy_limit) ||
            buycount + Number(goods.index_order_count) >
              Number(goods.index_buy_limit))
        ) {
          wx.showModal({
            title: '提示',
            content: '本商品每月限购' + goods.index_buy_limit + '件',
            showCancel: false,
            success(res) {},
          });
          return false;
        }
      } else {
        wx.showModal({
          title: '提示',
          content: '您还不是VIP会员,是否前往购买？',
          success(res) {
            if (res.confirm) {
              app.util.navigateTo(
                '/ws_micro_shop/pages/recharge/recharge?from=nianka'
              );
            }
          },
        });
        return false;
      }
    }

    if (!_this.data.show_attr_picker) {
      _this.setData({
        show_attr_picker: true,
      });
      return true;
    }
    if (
      _this.data.miaosha_data &&
      _this.data.miaosha_data.rest_num > 0 &&
      buycount > _this.data.miaosha_data.rest_num
    ) {
      wx.showToast({
        title: '商品库存不足，请选择其它规格或数量',
        icon: 'none',
      });
      return true;
    }
    if (buycount > _this.data.goods.num) {
      wx.showToast({
        title: '商品库存不足，请选择其它规格或数量',
        icon: 'none',
      });
      return true;
    }
    let attr_group_list = _this.data.attr_group_list;
    let checked_attr_list = [];
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let attr = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            attr = {
              attr_id: attr_group_list[i].attr_list[j].attr_id,
              attr_name: attr_group_list[i].attr_list[j].attr_name,
            };
            break;
          }
        }
        if (!attr) {
          wx.showToast({
            title: '请选择' + attr_group_list[i].attr_group_name,
            icon: 'none',
          });
          return true;
        } else {
          checked_attr_list.push({
            attr_group_id: attr_group_list[i].attr_group_id,
            attr_group_name: attr_group_list[i].attr_group_name,
            attr_id: attr.attr_id,
            attr_name: attr.attr_name,
          });
        }
      }
    }
    // 限购判断 by--lili
    if (goods.limit_count > 0) {
      let able_num =
        goods.limit_count -
        goods.user_order_count.cart -
        goods.user_order_count.order;
      if (buycount > able_num) {
        wx.showToast({
          title: '当前最大购买数量为' + able_num,
          icon: 'none',
        });
        return;
      }
    }
    if (type === 'ADD_CART') {
      gatherAction &&
        gatherAction('addCart', 'success', { goodsID: this.data.id });
      wx.showLoading({
        title: '正在提交',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.cart.add_cart,
        method: 'POST',
        data: {
          goods_id: _this.data.id,
          attr: JSON.stringify(checked_attr_list),
          num: buycount,
        },
        success: function(res) {
          wx.showToast({
            title: res.msg || '',
            icon: Number(res.code) === 0 ? 'success' : 'none',
          });
          wx.hideLoading();
          _this.setData({
            show_attr_picker: Number(res.code) === 1,
            'goods.user_order_count.cart':
              Number(goods.user_order_count.cart) + (Number(res.code) === 1 ? 0 : buycount),
          });
        },
      });
    }
    if (type === 'BUY_NOW') {
      gatherAction &&
        gatherAction('buyNow', 'success', { goodsID: this.data.id });
      _this.setData({
        show_attr_picker: false,
      });
      wx.navigateTo({
        url:
          '/ws_micro_shop/pages/order-submit/order-submit?goods_info=' +
          JSON.stringify({
            goods_id: _this.data.id,
            attr: checked_attr_list,
            num: buycount,
            matchGoods: _this.data.matchGoods,
          }),
      });
    }
  },

  hideAttrPicker() {
    this.setData({
      show_attr_picker: false,
      show_attr_integral: false,
      show_attr_coupon: false,
      show_parameter: false,
    });
  },

  integral() {
    this.setData({
      show_attr_integral: true,
    });
    let list = wx.getStorageSync('store');
    this.setData({
      integral: list['integration'],
    });
  },

  coupon() {
    this.setData({
      show_attr_coupon: true,
    });
  },

  disabledClick() {
    // it`s necessary
  },

  showAttrPicker() {
    this.setData({
      show_attr_picker: true,
    });
  },
  showParameter() {
    this.setData({
      show_parameter: true,
    });
  },
  attrClick(e) {
    let _this = this;
    let attr_group_id = Number(e.currentTarget.dataset.groupId);
    let attr_id = Number(e.target.dataset.id);
    let attr_group_list = _this.data.attr_group_list;
    for (let i in attr_group_list) {
      if (Number(attr_group_list[i].attr_group_id) !== attr_group_id) {
        continue;
      }
      for (let j in attr_group_list[i].attr_list) {
        if (Number(attr_group_list[i].attr_list[j].attr_id) === attr_id) {
          attr_group_list[i].attr_list[j].checked = true;
        } else {
          attr_group_list[i].attr_list[j].checked = false;
        }
      }
    }
    _this.setData({
      attr_group_list,
    });
    let check_attr_list = [];
    let check_all = true;
    for (let i in attr_group_list) {
      if (Object.prototype.hasOwnProperty.call(attr_group_list, i)) {
        let group_checked = false;
        for (let j in attr_group_list[i].attr_list) {
          if (attr_group_list[i].attr_list[j].checked) {
            check_attr_list.push(attr_group_list[i].attr_list[j].attr_id);
            group_checked = true;
            break;
          }
        }
        if (!group_checked) {
          check_all = false;
          break;
        }
      }
    }
    if (!check_all) {
      return;
    }
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.default.goods_attr_info,
      data: {
        goods_id: _this.data.goods.id,
        attr_list: JSON.stringify(check_attr_list),
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let goods = _this.data.goods;
          res.data.origin_price && (goods.original_price = res.data.origin_price);
          res.data.oriprice && (goods.oriprice = res.data.oriprice);
          goods.price = res.data.price;
          goods.num = res.data.num;
          goods.weight = res.data.weight;
          goods.attr_pic = res.data.pic;
          goods.limit_count = res.data.limit_count;
          goods.user_order_count = res.data.user_order_count;
          goods.concession_start = res.data.concession_start;
          goods.concession_end = res.data.concession_end;
          goods.min_num = Number(res.data.min_num);
          _this.setData({
            goods,
            // miaosha_data: res.data.miaosha,
          });
        }
      },
    });
  },

  favoriteAdd() {
    let _this = this;
    app.ws_micro_shoprequest({
      url: api.user.favorite_add,
      method: 'post',
      data: {
        goods_id: _this.data.goods.id,
      },
      success: function(res) {
        if (res.code === 0) {
          wx.showToast({
            title: '收藏成功',
            icon: 'success',
            duration: 1500,
          })
          let goods = _this.data.goods;
          goods.is_favorite = 1;
          _this.setData({
            goods,
          });
        }
      },
    });
    gatherAction &&
      gatherAction('favoriteAdd', 'success', { goodsID: this.data.id });
  },

  favoriteRemove() {
    let _this = this;
    app.ws_micro_shoprequest({
      url: api.user.favorite_remove,
      method: 'POST',
      data: {
        goods_id: _this.data.goods.id,
      },
      success: function(res) {
        if (res.code === 0) {
          wx.showToast({
            title: '已取消收藏',
            icon: 'success',
            duration: 1500,
          })
          let goods = _this.data.goods;
          goods.is_favorite = 0;
          _this.setData({
            goods,
          });
        }
      },
    });
    gatherAction &&
      gatherAction('favoriteRemove', 'success', { goodsID: this.data.id });
  },

  commentPicView(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    let pic_index = e.currentTarget.dataset.pic_index;
    wx.previewImage({
      current: _this.data.comment_list[index].pic_list[pic_index],
      urls: _this.data.comment_list[index].pic_list,
    });
    gatherAction &&
      gatherAction('commentPicView', 'success', { goodsID: this.data.id });
  },

  onReachBottom() {},

  onShareAppMessage() {
    let _this = this;
    let user_info = wx.getStorageSync('user_info');
    let path =
      '/ws_micro_shop/pages/goods/goods?id=' +
      this.data.id +
      '&user_id=' +
      user_info.id +
      '&tabbarindex=' +
      app.tabbarindex +
      '&shopid=' +
      app.ws_micro_shop_globalData.shopid;
    path = util.spliceSharePath(path, '4', moduleName);
    app.shareSendCoupon(_this);
    gatherAction &&
      gatherAction('onShareGoodsMessage', 'success', { goodsID: this.data.id });
    let shareShowPrice =
      wx.getStorageSync('store') && wx.getStorageSync('store').share_show_price;
    let res = {
      path,
      title: `${
        Number(shareShowPrice) === 1 ? _this.data.goods.price + '元' : ''
      }${_this.data.goods.name}`,
      imageUrl: _this.data.goods.pic_list[0].pic_url,
    };
    return res;
  },

  onShareTimeline() {
    let _this = this;
    let user_info = wx.getStorageSync('user_info');
    app.shareSendCoupon(_this);
    let shareShowPrice =
      wx.getStorageSync('store') && wx.getStorageSync('store').share_show_price;
    return {
      title: `${
        Number(shareShowPrice) === 1 ? _this.data.goods.price + '元' : ''
      }${_this.data.goods.name}`,
      imageUrl: _this.data.goods.pic_list[0].pic_url,
      query: 'id=' +
      this.data.id +
      '&user_id=' +
      user_info.id +
      '&tabbarindex=' +
      app.tabbarindex +
      '&shopid=' +
      app.ws_micro_shop_globalData.shopid
    }
  },

  play(e) {
    let url = e.target.dataset.url;
    this.setData({
      url: url,
      hide: '',
      autoplay: false,
    });
    let videoContext = wx.createVideoContext('video');
    videoContext.play();
    gatherAction &&
      gatherAction('playGoodsVideo', 'success', { goodsID: this.data.id });
  },

  close(e) {
    this.setData({
      hide: 'hide',
      autoplay: true,
    });
    let videoContext = wx.createVideoContext('video');
    videoContext.pause();
  },

  hide(e) {
    if (Number(e.detail.current) === 0) {
      this.setData({
        img_hide: true,
      });
    } else {
      this.setData({
        img_hide: false,
      });
    }
  },

  showShareModal() {
    this.setData({
      share_modal_active: 'active',
      no_scroll: true,
    });
  },

  shareModalClose() {
    this.setData({
      share_modal_active: '',
      no_scroll: false,
    });
  },

  getGoodsQrcode() {
    let _this = this;
    _this.setData({
      goods_qrcode_active: 'active',
      share_modal_active: '',
    });
    if (_this.data.goods_qrcode) {
      return true;
    }
    app.ws_micro_shoprequest({
      url: api.default.goods_qrcode,
      data: {
        goods_id: _this.data.id,
      },
      success: function(res) {
        if (res.code === 0) {
          _this.setData({
            goods_qrcode: res.data.pic_url,
          });
        }
        if (res.code === 1) {
          _this.goodsQrcodeClose();
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
    gatherAction &&
      gatherAction('userGetGoodsQrcode', 'success', { goodsID: this.data.id });
  },

  goodsQrcodeClose() {
    this.setData({
      goods_qrcode_active: '',
      no_scroll: false,
    });
  },

  saveGoodsQrcode() {
    let _this = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content:
          '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
          _this.downLoadGoodsImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          _this.setData({
            open_setting: true,
          });
        } else {
          _this.downLoadGoodsImg();
        }
      },
    });
    gatherAction &&
      gatherAction('userSaveGoodsQrcode', 'success', { goodsID: this.data.id });
  },

  downLoadGoodsImg() {
    let _this = this;
    wx.showLoading({
      title: '正在下载图片',
      mask: true,
    });
    wx.downloadFile({
      url: _this.data.goods_qrcode,
      success: function(e) {
        wx.showLoading({
          title: '正在保存图片',
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function() {
            wx.showModal({
              title: '提示',
              content: '商品海报保存成功',
              showCancel: false,
            });
          },
          fail: function(e) {
            wx.showModal({
              title: '提示',
              content: '图片保存失败',
              showCancel: false,
            });
          },
          complete: function(e) {
            wx.hideLoading();
          },
        });
      },
      fail: function(e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + _this.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function(e) {
        wx.hideLoading();
      },
    });
  },

  goodsQrcodeClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },

  closeCouponBox(e) {
    this.setData({
      get_coupon_list: '',
    });
  },

  setMiaoshaTimeOver() {
    let _this = this;
    function _init() {
      let time_over =
        _this.data.goods.miaosha.end_time - _this.data.goods.miaosha.now_time;
      time_over = time_over < 0 ? 0 : time_over;
      _this.data.goods.miaosha.now_time++;
      _this.setData({
        goods: _this.data.goods,
        miaosha_end_time_over: secondToTime(time_over),
      });
    }
    _init();
    setInterval(function() {
      _init();
    }, 1000);
    function secondToTime(second) {
      let _h = parseInt(second / 3600, 10);
      let _m = parseInt((second % 3600) / 60, 10);
      let _s = second % 60;
      return {
        h: _h < 10 ? '0' + _h : String(_h),
        m: _m < 10 ? '0' + _m : String(_m),
        s: _s < 10 ? '0' + _s : String(_s),
      };
    }
  },

  to_dial() {
    let contact_tel = this.data.store.contact_tel;
    wx.makePhoneCall({
      phoneNumber: contact_tel,
    });
    gatherAction &&
      gatherAction('makePhoneCall', 'success', { goodsID: this.data.id });
  },

  openService() {
    this.setData({
      show_service: true,
    });
    gatherAction &&
      gatherAction('openService', 'success', { goodsID: this.data.id });
  },

  closeService() {
    this.setData({
      show_service: false,
    });
  },

  onNavigate(e) {
    let param = e.currentTarget.dataset;
    if (param.type == 'cart' && this.data.isMulti && app.ws_micro_shop_globalData.shopid == 0) {
      app.ws_micro_shop_globalData.fromHome = true;
    }
    app.ws_micro_shop_navigate(param);
  },

  downloadPicture() {
    utils.downLoad(this);
    gatherAction &&
      gatherAction('downLoadGoodsImg', 'success', { goodsID: this.data.id });
  },

  wxmlTagATap(e) {
    let src = e.detail.src || false;
    let reUrl = /^\//;
    if (!src) {
      return;
    } else {
      if (reUrl.test(src)) {
        app.util.navigateTo('/ws_micro_shop' + src);
      } else {
        app.util.navigateTo('/ws_micro_shop/pages/web/web', { url: src });
      }
    }
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  tabMiniCard(e) {
    let args = e.detail;
    console.log(args);
    let currentPath = '';
    let pages = getCurrentPages();
    pages.length > 0 && (currentPath = '/' + pages.pop().route);
    console.log(currentPath, args.path);
    console.log(this.data.opts.id, args.query);

    (currentPath !== args.path ||
      String(this.data.opts.id) !== args.query.id) &&
      setTimeout(() => {
        app.util.navigateTo(args.path, args.query);
      }, 500); // 跳转到tabbar页面，如果不加延时，会出现reLaunch错误。
  },

  showReplyBox(e) {
    let { replyid, host } = e.currentTarget.dataset;
    this.setData({
      showreply: true,
      mainid: replyid,
      host,
    });
    this.loadCommentList();
  },

  showReplyBox2(e) {
    let { replyid } = e.currentTarget.dataset;
    this.setData({
      showInput: true,
      replyid,
      replycontent: '',
    });
  },

  hideReplyBox() {
    this.setData({
      showreply: false,
      commentlist: [],
      cPage: 1,
      cMore: true,
    });
  },

  getReplyContent(e) {
    this.setData({
      replycontent: e.detail.value.trim(),
    });
  },

  replySubmit() {
    let that = this;
    let { replycontent, replyid, commentlist } = this.data;
    if (replycontent) {
      app.ws_micro_shoprequest({
        url: api.default.replycomment,
        method: 'POST',
        data: {
          id: replyid,
          content: replycontent,
        },
        success: function(res) {
          if (res.code === 0) {
            wx.showToast({
              title: '评论成功',
            });
            commentlist.unshift(res.data);
            that.setData({
              replycontent: '',
              showInput: false,
              commentlist,
            });
          }
        },
      });
    } else {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none',
      });
    }
  },

  showReplyInput(e) {
    this.setData({
      showInput: true,
      replyid: e.currentTarget.dataset.hostid,
    });
  },

  hideInput() {
    if (!this.data.replycontent) {
      this.setData({
        showInput: false,
      });
    }
  },

  loadCommentList() {
    let that = this;
    let { commentlist, cPage, cMore, mainid } = that.data;
    if (cMore) {
      app.ws_micro_shoprequest({
        url: api.default.getcomment,
        data: {
          id: mainid,
          page: cPage,
          limit: 20,
        },
        success: function(res) {
          if (res.code === 0) {
            let list = res.data.list;
            if (list.length > 0) {
              cPage += 1;
              that.setData({
                commentlist: commentlist.concat(list),
                cPage,
              });
            } else {
              that.setData({
                cMore: false,
              });
              wx.showToast({
                title: '没有更多评论了',
                icon: 'none',
              });
            }
          } else {
            wx.showToast({
              title: res.msg || '',
              icon: 'none',
            });
          }
        },
      });
    }
  },

  loadGoodsRecommend(id) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.default.recommend,
      data: {
        goods_id: id,
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            recommendlist: res.data,
          });
        } else {
          wx.showToast({
            title: res.msg || '',
            icon: 'none',
          });
        }
      },
    });
  },

  checkGoods(e) {
    app.util.navigateTo(
      '/ws_micro_shop/pages/goods/goods',
      { id: e.currentTarget.dataset.gid },
      true
    );
  },

  addMatchGoods(e) {
    let { goodsId } = e.currentTarget.dataset;
    let { matchGoods } = this.data;
    goodsId &&
      this.setData({
        matchGoods:
          matchGoods.indexOf(goodsId) >= 0
            ? (matchGoods.splice(matchGoods.indexOf(goodsId), 1), matchGoods)
            : [...matchGoods, goodsId],
      });
  },

  getFloatIcon() {
    let that = this;
    let {
      dial,
      dial_pic,
      contact_tel,
      web_service,
      web_service_url,
      show_customer_service,
      serviceMessageTitle,
      serviceMessagePath,
      service,
      show_qywxcustomer_service,
      show_qywxcustomer_pic,
      card_toopenid,
      card_openid,
      card_id
    } = that.data;
    let floatItems = [
      {
        type: 1, // 客服电话
        show: Number(dial) === 1,
        icon: dial_pic,
        tel: contact_tel,
      },
      {
        type: 6, // 企业客服
        show: Number(show_qywxcustomer_service) === 1,
        icon: show_qywxcustomer_pic,
      },
      {
        type: 3, // webview跳转
        show: web_service,
        icon: web_service,
        url: web_service_url,
      },
      {
        type: 0, // 推荐
        show: false,
        iconClass: 'icon icon-xin',
        event: 'recommend',
      }
    ];
    let customerlist;
    if (Number(show_customer_service) === 1) {
      customerlist = [
        {
          type: 4, // 客服跳转
          show: true,
          icon: service,
          sessionFormStr: JSON.stringify({
            shop_id: app.ws_micro_shop_globalData.shopid,
          }),
          serviceMessageTitle: serviceMessageTitle,
          serviceMessagePath: serviceMessagePath,
        }
      ]
    } else if (Number(show_customer_service) === 2 || Number(show_customer_service) === 3) {
      customerlist = [
        {
          type: 7, //内部跳转
          show: true,
          icon: service,
          url: '/common/component/universal-card/pages/message?openid=' + card_openid + '&to_openid=' + card_toopenid + '&cardid=' + card_id + '&scene=inner&m_id=0'
        },
      ]
    }
    customerlist && (floatItems = floatItems.concat(customerlist));
    that.setData({
      floatItems
    },() => {
      this.checkUserCardManage();
    });
  },
  customerTo() {
    let { card_openid, card_toopenid, card_id } = this.data;
    let url = '/common/component/universal-card/pages/message?openid=' + card_openid + '&to_openid=' + card_toopenid + '&cardid=' + card_id + '&scene=inner&m_id=0';
    app.util.navigateTo(url);
  },

  receive(e) {
    let _this = this;
    let id = e.currentTarget.dataset.index;
    app.ws_micro_shoprequest({
      url: api.coupon.receive,
      data: {
        id: id,
      },
      showLoading: true,
      success: function(res) {
        if (res.code === 0) {
          wx.showToast({
            title: '领取成功',
            icon: 'none',
            duration: 2000,
          });
          _this.getGoods();
        }
        if (res.code === 1) {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000,
          });
        }
      },
    });
  },

  // 判断当前模块是否开启了推荐
  checkRecommandBtn(){
    let { floatItems } = this.data;
    app.util.request({
      url:'card/record/getModuleRecommandButton',
      success: res => {
        let {errcode, data} = res.data;
        if(errcode == 0){
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.show = data == 1? true: false;
            }
          })
          this.setData({
            floatItems
          })
        }
      }
    })
  },

  // 判断当前用户是否有名片及商品是否被加入到名片推荐商品中
  checkUserCardManage(){
    let { id } = this.options;
    let { floatItems } = this.data;
    app.util.request({
      url:'card/record/getUserCardManage',
      data:{
        id,
        type:'1',
        openid: wx.getStorageSync('openid') || wx.getStorageSync('OPENID')
      },
      success: res => {
        let {errcode, data:{is_cardmanage,is_havegoods}} = res.data;
        console.log("=====checkUserCardManage====",res.data);
        this.checkRecommandBtn();
        if(errcode == 0){
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.show = is_cardmanage == 1? true: false;
              item.iconClass = is_havegoods == 1? 'icon icon-xinxin' :'icon icon-xin';
            }
          })
          this.setData({
            floatItems,
            is_havegoods
          })
        }
      }
    })
  },
  

  // 添加推荐商品
  recommend(){
    let { id } = this.options;
    let { floatItems, is_havegoods } = this.data;
    console.log("===is_havegoods====",is_havegoods)
    app.util.request({
      url:'card/record/addCardManageGoods',
      data:{
        id,
        type:'1',
        openid: wx.getStorageSync('openid') || wx.getStorageSync('OPENID'),
        options: is_havegoods == 0? '1': '2'
      },
      success: res => {
        console.log("===addCardManageGoods====",res.data.data)
        if(res.data.errcode == 0){
          is_havegoods = !is_havegoods;
          floatItems.forEach(item =>{
            if(item.event == 'recommend'){
              item.iconClass = is_havegoods == 1? 'icon icon-xinxin' :'icon icon-xin';
            }
          })
          let title = is_havegoods == 1?'推荐成功':'取消推荐成功';
          wx.showToast({
            title,
            icon:'none'
          })
        } else {
          wx.showToast({
            title:res.data.errmsg,
            icon:'none'
          })
        }
        this.setData({
          floatItems,
          is_havegoods
        })
      }
    })
  },
});
